<?php

namespace App\Listeners\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\UserBaseInfoEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserContractEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserExperienceEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserIdentityCardEnum;
use App\Events\OpenShop\OrderEditedEvent;
use App\Listeners\BaseListener;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderLogModel;
use App\Service\OpenShop\User\RmsUserService;
use GuzzleHttp\Exception\GuzzleException;

class OrderEditedLogListener extends BaseListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Handle the event.
     *
     * @param OrderEditedEvent $event
     * @return void
     * @throws GuzzleException
     */
    public function handle(OrderEditedEvent $event)
    {
        $baseInfo = [];
        foreach ($event->originalBaseInfo as $k => $old) {
            $new = $event->newBaseInfo[$k] ?? null;
            if ($old === $new) {
                continue;
            }
            switch ($k) {
                case 'mobile':
                    $baseInfo[] = "注册手机号：{$old} => {$new}";
                    break;
                case 'remarkMobile1':
                    $baseInfo[] = "备注手机号1：{$old} => {$new}";
                    break;
                case 'remarkMobile2':
                    $baseInfo[] = "备注手机号2：{$old} => {$new}";
                    break;
                case 'weChatNumber':
                    $baseInfo[] = "微信号：{$old} => {$new}";
                    break;
                case 'isMarried':
                    $baseInfo[] = "婚姻状况：" . (2 == $old ? '已' : '未') . "婚 => " . (2 == $new ? '已' : '未') . '婚';
                    break;
                case 'addressPrefix':
                    $baseInfo[] = "三级地址：{$old} => {$new}";
                    break;
                case 'address':
                    $baseInfo[] = "详细地址：{$old} => {$new}";
                    break;
                case 'postCode':
                    $baseInfo[] = "邮编：{$old} => {$new}";
                    break;
                case 'source':
                    $baseInfo[] = "来源：" . (UserBaseInfoEnum::SOURCE[$old] ?? '-') . " => " . (UserBaseInfoEnum::SOURCE[$new] ?? '-');
                    break;
                case 'isSelfManaged':
                    $baseInfo[] = "亲自经营：" . (2 == $old ? '是' : '否') . " => " . (2 == $new ? '是' : '否');
                    break;
                case 'joinReason':
                    $baseInfo[] = "加盟原因：" . (UserBaseInfoEnum::JOIN_REASON[$old] ?? '-') . " => " . (UserBaseInfoEnum::JOIN_REASON[$new] ?? '-');
                    break;
                case 'shopBudget':
                    $baseInfo[] = "开店预算：{$old}万元 => {$new}万元";
                    break;
                case 'investmentMode':
                    $baseInfo[] = "投资方式：" . (UserBaseInfoEnum::INVESTMENT_MODE[$old] ?? '-') . " => " . (UserBaseInfoEnum::INVESTMENT_MODE[$new] ?? '-');
                    break;
                case 'financeSource':
                    $baseInfo[] = "资金来源：" . (UserBaseInfoEnum::FINANCE_SOURCE[$old] ?? '-') . " => " . (UserBaseInfoEnum::FINANCE_SOURCE[$new] ?? '-');
                    break;
                case 'isSelfWithAddress':
                    $baseInfo[] = "自带选址：" . (UserBaseInfoEnum::SELF_WITH_ADDRESS == $old ? '是' : '否') . " => " . (UserBaseInfoEnum::SELF_WITH_ADDRESS == $new ? '是' : '否');
                    break;
                case 'shopAddressPrefix':
                    $baseInfo[] = "意向门店三级地址：{$old} => {$new}";
                    break;
                case 'chooseShopAddressPrefix':
                    $baseInfo[] = "门店选址三级地址：{$old} => {$new}";
                    break;
                case 'shopName':
                    $baseInfo[] = "意向门店名字：{$old} => {$new}";
                    break;
                case 'shopAddress':
                    $baseInfo[] = "意向门店地址：{$old} => {$new}";
                    break;
                case 'chooseAddressReason':
                    $baseInfo[] = "选址原因：" . (UserBaseInfoEnum::CHOOSE_ADDRESS_REASON[$old] ?? '-') . " => " . (UserBaseInfoEnum::CHOOSE_ADDRESS_REASON[$new] ?? '-');
                    break;
                case 'email':
                    $baseInfo[] = "Email：{$old} => {$new}";
                    break;
            }
        }
        // 身份信息
        $userIdentity = [];
        foreach ($event->originalUserIdentity as $k => $old) {
            $new = $event->newUserIdentity[$k] ?? null;
            if ($old === $new) {
                continue;
            }
            switch ($k) {
                case 'name':
                    $userIdentity[] = "身份证姓名：{$old} => {$new}";
                    break;
                case 'identityCardNumber':
                    $userIdentity[] = "身份证号码：{$old} => {$new}";
                    break;
                case 'gender':
                    $userIdentity[] = "性别：" . (UserIdentityCardEnum::GENDER_2 == $old ? '男' : '女') . " => " . (UserIdentityCardEnum::GENDER_2 == $new ? '男' : '女');
                    break;
                case 'effectiveStartTime':
                    $userIdentity[] = "身份证有效期开始日期：" . date('Y-m-d', $old) . " => " . date('Y-m-d', $new);
                    break;
                case 'effectiveEndTime':
                    $userIdentity[] = "身份证有效期结束日期：" . date('Y-m-d', $old) . " => " . date('Y-m-d', $new);
                    break;
                case 'nativePlace':
                    $userIdentity[] = "籍贯：{$old} => {$new}";
                    break;
                case 'nation':
                    $userIdentity[] = "民族：{$old} => {$new}";
                    break;
                case 'birthday':
                    $userIdentity[] = "生日：{$old} => {$new}";
                    break;
                case 'animalSign':
                    $userIdentity[] = "生肖：{$old} => {$new}";
                    break;
                case 'constellation':
                    $userIdentity[] = "星座：{$old} => {$new}";
                    break;
            }
        }
        // 工作经历
        $experience = [];
        foreach ($event->originalWorkExperience as $k => $old) {
            $new = $event->newWorkExperience[$k] ?? null;
            if ($old === $new) {
                continue;
            }
            switch ($k) {
                case 'cateringExperience':
                    $experience[] = "餐饮经验：" . (UserExperienceEnum::CATERING_EXPERIENCE[$old] ?? '-') . " => " . (UserExperienceEnum::CATERING_EXPERIENCE[$new] ?? '-');
                    break;
                case 'joinChainExperience':
                    $experience[] = "是否有加盟连锁经验：" . (UserExperienceEnum::HAS_EXPERIENCE[$old] ?? '-') . " => " . (UserExperienceEnum::HAS_EXPERIENCE[$new] ?? '-');
                    break;
                case 'employmentExperience':
                    $experience[] = "是否有自营经验：" . (UserExperienceEnum::HAS_EXPERIENCE[$old] ?? '-') . " => " . (UserExperienceEnum::HAS_EXPERIENCE[$new] ?? '-');
                    break;
                case 'workLife':
                    $experience[] = "工作年限：" . (UserExperienceEnum::WORK_LIFE[$old] ?? '') . " => " . (UserExperienceEnum::WORK_LIFE[$new] ?? '-');
                    break;
            }
        }
        // 合同内容变更
        $contract = [];
        foreach ($event->beforeContract as $k => $old) {
            $new = $event->afterContract[$k] ?? null;
            if ($old === $new) {
                continue;
            }
            switch ($k) {
                case 'contractExtNo':
                    $contract[] = "第三方合同编号：{$old} => {$new}";
                    break;
                case 'contractors':
                    $contract[] = "签约主题：" . (UserContractEnum::CONTRACTORS[$old] ?? '-') . ' => ' . (UserContractEnum::CONTRACTORS[$new] ?? '-');
                    break;
                case 'companyName':
                    $contract[] = "公司名称：{$old} => {$new}";
                    break;
                case 'businessLicenseNumber':
                    $contract[] = "营业执照号：{$old} => {$new}";
                    break;
                case 'startTime':
                    $contract[] = "合同开始时间：" . date('Y-m-d', $old) . ' => '. date('Y-m-d', $new);
                    break;
                case 'endTime':
                    $contract[] = "合同截止时间：" . date('Y-m-d', $old) . ' => '. date('Y-m-d', $new);
                    break;
                case 'contractType':
                    $contract[] = "签约类型：" . (UserContractEnum::CONTRACT_TYPE[$old] ?? '-') . ' => ' . (UserContractEnum::CONTRACT_TYPE[$new] ?? '-');
                    break;
                case 'policyTemplateId':
                    $oldName = (string)OpenShopContractTemplateModel::query()
                        ->where('id', $old)
                        ->value('templateName');
                    $newName = (string)OpenShopContractTemplateModel::query()
                        ->where('id', $new)
                        ->value('templateName');
                    $contract[] = "政策模版：{$oldName} => {$newName}";
                    break;
                case 'remark':
                    $contract[] = "内部备注：{$old} => {$new}";
                    break;
                case 'year':
                    $contract[] = "合同年限：{$old} => {$new}";
                    break;
                case 'initialFee':
                    $contract[] = "加盟费：" . ($old / 100) . ' => ' . ($new / 100);
                    break;
                case 'technologyTransferFee':
                    $contract[] = "技术转让费：" . ($old / 100) . ' => ' . ($new / 100);
                    break;
                case 'deposit':
                    $contract[] = "保证金：" . ($old / 100) . ' => ' . ($new / 100);
                    break;
                case 'managementCost':
                    $contract[] = "特许权使用费第一年：" . ($old / 100) . ' => ' . ($new / 100);
                    break;
                case 'decorationDeposit':
                    $contract[] = "装修保证金：" . ($old / 100) . ' => ' . ($new / 100);
                    break;
                case 'shopCount':
                    $contract[] = "店铺数量：{$old} => {$new}";
                    break;
            }
        }
        $changes = '';
        if (count($userIdentity)) {
            $changes .= "\n\n🆔用户身份信息：" . PHP_EOL;
            $changes .= implode(PHP_EOL, $userIdentity);
        }
        if (count($baseInfo)) {
            $changes .= "\n\n🆔用户身份信息：" . PHP_EOL;
            $changes .= implode(PHP_EOL, $baseInfo);
        }
        if (count($experience)) {
            $changes .= "\n\n🧑‍🏫工作经验：" . PHP_EOL;
            $changes .= implode(PHP_EOL, $experience);
        }
        if (count($contract)) {
            $changes .= "\n\n✍️修改订单合同\n";
            $changes .= implode(PHP_EOL, $contract);
        }

        $changes = trim($changes, "\n");
        if (!strlen($changes)) {
            return;
        }
        $body              = RmsUserService::getRmsUserInfoByUserIds([$event->rmsUserId]);
        $username          = $body['data'][0]['username'] ?? "用户ID:{$event->rmsUserId}";
        $log               = new OpenShopSignOrderLogModel;
        $log->orderId      = $event->originalOrderData['id'];
        $log->content      = "修改开店订单";
        $log->type         = OpenShopSignOrderLogModel::TYPE_ORDER_EDITED;
        $log->operatorName = $username;
        $log->changes      = $changes;
        $log->createdAt    = strtotime($event->datetime);
        $log->updatedAt    = strtotime($event->datetime);
        $log->createdByUid = $event->rmsUserId;
        $log->updatedByUid = $event->rmsUserId;
        $log->save();
    }
}
